<template>
  <el-dialog
    top="30px"
    append-to-body
    title="选择新增政府机构"
    width="600px"
    :visible.sync="visible"
    :close-on-click-modal="false"
    :before-close="beforeClose"
  >
    <div class="content">
      <div class="d-flex">
        <div :class="cityIndex > -1 && 'border-right'">
          <el-scrollbar
            v-if="cityGov.length"
            tag="ul"
            wrap-class="c-area-dropdown__wrap"
            view-class="el-select-dropdown__list"
            ref="scrollbarCity"
          >
            <li v-if="cityGov.length" class="el-cascader-node">
              <el-checkbox
                :indeterminate="cityAllIndeterminate"
                v-model="cityAllChecked"
                @change="handleAllItemChecked"
              >
                <div class="c-area__label-text pl-1">全选</div>
              </el-checkbox>
            </li>
            <li
              v-for="(item, index) in cityGov"
              :key="item.agency_id"
              class="el-cascader-node"
              :class="{ 'is-active': item.checked, 'in-checked-path': cityIndex === index }"
              @click.stop="handleCityItemClick(item, index)"
            >
              <el-checkbox
                :indeterminate="item.indeterminate"
                v-model="item.checked"
                @click.stop
                @change="handleCityItemChecked(item, index)"
              ></el-checkbox>
              <span class="c-area__label">{{ item.agency_name }}</span>
              <template>
                <i v-if="item.loading" class="el-icon-loading el-cascader-node__postfix"></i>
                <i v-else class="el-icon-arrow-right el-cascader-node__postfix"></i>
              </template>
            </li>
          </el-scrollbar>
          <div v-else class="c-area__empty-text">暂无机构</div>
        </div>
        <div v-if="cityIndex > -1">
          <el-scrollbar
            v-if="countyOptions.length"
            tag="ul"
            wrap-class="c-area-dropdown__wrap"
            view-class="el-select-dropdown__list"
            ref="scrollbarCounty"
          >
            <!-- <li class="el-cascader-node">
            <el-checkbox v-model="countyAllChecked"
                         @change="handleAllCountyChecked">
              <div class="c-area__label-text pl-1">全选</div>
            </el-checkbox>
          </li> -->
            <li
              v-for="(item, index) in countyOptions"
              :key="item.id"
              class="el-cascader-node"
              :class="{ 'is-active': item.isChecked, 'in-checked-path': item.inCheckedPath }"
            >
              <el-checkbox
                :indeterminate="item.indeterminate"
                v-model="item.checked"
                @change="handleCountyItemChecked(item, index)"
              >
                <div class="c-area__label-text">{{ item.agency_name }}</div>
              </el-checkbox>
            </li>
          </el-scrollbar>
          <div v-else class="c-area__empty-text">暂无机构</div>
        </div>
      </div>
      <div class="text-center">
        <el-button type="primary" class="btn-long" @click="OnSave">保存</el-button>
        <el-button @click="beforeClose" class="btn-long">取消</el-button>
      </div>
    </div>
  </el-dialog>
</template>

<script>
import { mapGetters } from 'vuex'
import { addressFromLevel, addressCut } from '@vimi/utils-tool'

export default {
  props: {
    visible: Boolean,
  },
  data() {
    return {
      params: {
        'agency_type.eq': 3,
      },
      tableName: 'credit_agency_info',
      cityIndex: -1,
      countyIndex: -1,
      cityGov: [],
      countyOptions: [],
      cityAllIndeterminate: false,
      cityAllChecked: false,
      countyAllChecked: false,
    }
  },

  computed: {
    ...mapGetters(['user', 'clientId']),
    queryAddressCode() {
      return this.user.queryAddressCode
    },
    orgRegionLever() {
      return this.user.orgRegionLever
    },
  },

  created() {
    this.params.address_code = addressFromLevel(this.queryAddressCode, 1)
    this.params['org_region_lever.in'] = '2,3'

    this.getData()
  },
  methods: {
    OnSave() {
      const data = []
      this.cityGov.forEach(item => {
        if (item.checked) {
          data.push(item)
        }
        item.children.forEach(child => {
          if (child.checked) {
            data.push(child)
          }
        })
      })

      if (!data.length) {
        return this.$message.warning('请先选择需要新增的政府机构')
      }
      const putData = []
      data.forEach(item => {
        putData.push({
          service_id: this.clientId,
          access_agency_id: item.agency_id,
          access_status: 1,
        })
      })
      this.$msgbox({
        title: '提示',
        message: `确认新增已选政府机构 ？`,
        showCancelButton: true,
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        beforeClose: async (action, instance, done) => {
          if (action === 'confirm') {
            instance.confirmButtonText = '操作中...'
            instance.confirmButtonLoading = true
            await this.$api
              .addBatch(this.$serviceName, 'credit_agency_access', putData)
              .then(() => {
                this.$message.success('添加成功')
                this.beforeClose()
                this.$emit('success', true)
              })
              .catch(() => {
                this.$message.error('添加失败')
              })
            instance.confirmButtonLoading = false
            instance.confirmButtonText = '确定'
            done()
          } else {
            done()
          }
        },
      }).catch(() => {})
    },
    async getData() {
      this.cityGov = []
      this.loading = true
      const [res] = await this.fetchData(this.params)
      this.loading = false
      const address = addressCut(this.queryAddressCode)
      const data = (res && res.data) || []
      data.forEach(item => {
        if (+item.org_region_lever === 2 && !item.address_code.includes(address)) {
          item.checked = false
          item.loading = false
          item.children = []
          this.cityGov.push(item)
        }
      })
      this.cityGov.map(city => {
        city.children = []
        const tempAddress = addressCut(addressFromLevel(city.address_code, 2))
        data.forEach(item => {
          if (+item.org_region_lever === 3 && item.address_code.includes(tempAddress)) {
            item.checked = false
            item.loading = false
            city.children.push({ ...item })
          }
        })
        return city
      })
    },
    fetchData(params) {
      return this.$utils.promise(this.$api.getData(this.$serviceName, this.tableName, params))
    },
    async handleCityItemClick(row, index) {
      this.cityIndex = index
      this.countyIndex = -1
      this.countyOptions = row.children || []
    },
    handleCityItemChecked(row, index) {
      row.indeterminate = false
      this.changeCity(row, index)
      this.refreshChildren(row)
      // this.emitChange()
    },
    refreshChildren(row) {
      for (const child of row.children) {
        child.checked = row.checked
      }
    },
    handleCountyItemChecked(row, _index) {
      if (this.cityIndex > -1) {
        const cityOption = this.cityGov[this.cityIndex]
        cityOption.indeterminate = this.isIndeterminate(cityOption.children)
        const cityNextChecked = !cityOption.indeterminate && row.checked
        if (cityOption.checked !== cityNextChecked) {
          cityOption.checked = cityNextChecked
          this.changeCity(cityOption, this.cityIndex)
        }
      }
    },
    handleAllItemChecked() {
      this.cityIndex = -1
      this.cityAllIndeterminate = false
      for (const city of this.cityGov) {
        city.indeterminate = false
        city.checked = this.cityAllChecked
        for (const child of city.children) {
          child.indeterminate = false
          child.checked = this.cityAllChecked
        }
      }
    },
    handleAllCountyChecked() {
      this.cityGov[this.cityIndex].children.map(item => {
        item.checked = this.countyAllChecked
        return item
      })
    },
    changeCity(row, index) {
      this.cityAllIndeterminate = this.isIndeterminate(this.cityGov)
      this.cityAllChecked = !this.cityAllIndeterminate && row.checked
      this.handleCityItemClick(row, index)
    },
    isIndeterminate(data) {
      const { length } = data
      if (!length) return false
      for (let i = 1; i < length; i++) {
        if (data[i - 1].checked !== data[i].checked) {
          return true
        }
      }
      return false
    },
    beforeClose() {
      this.$emit('update:visible', false)
    },
  },
}
</script>
<style lang="scss" scoped>
.content {
  max-width: 550px;
  overflow: auto;
}
.c-area__empty-text {
  margin: 10px 0;
  padding: 145px 0;
  color: $gray-600;
  min-width: 200px;
  text-align: center;
}
.c-area__label {
  display: inline-block;
  white-space: nowrap;
  overflow: hidden;
  min-width: 155px;
}
.in-checked-path {
  color: $primary;
}
.c-area__label-text {
  min-width: 155px;
}
</style>
